package top.superflow.utils.regex

import java.util.regex.Pattern

import top.superflow.exception.Exceptable
import top.superflow.lang.StringUtils

import scala.collection.mutable.ListBuffer

object RegexUtils extends Exceptable{


  def extractValue(pattern : String, extractFrom : String, group : Int) : String = {
    if(StringUtils.isBlank(extractFrom)){
      return null
    }
    val routePattern = Pattern.compile(pattern);
    val matcher = routePattern.matcher(extractFrom);
    if(!matcher.find()){
      return null
    }

    val totalGroupCount = matcher.groupCount()
    if(totalGroupCount < group){
      throwRequestUnsupportedException("The group count {} is less than the expected group index {}", totalGroupCount, group)
    }

    matcher.group(group)

  }


  def extractAllGroup(groupPattern : String, extractFrom : String) : Array[String] = {
    if(StringUtils.isBlank(extractFrom)){
      return null
    }
    val routePattern = Pattern.compile(groupPattern);
    val matcher = routePattern.matcher(extractFrom);

    val matched = ListBuffer[String]()

    while (matcher.find()){
      matched += matcher.group(1)
    }

    matched.toArray
  }

  def escape(str : String) : String = {
    StringUtils.replaceAll(str, "(\\.|\\?|\\(|\\)|\\{|\\}|\\[|\\]|\\^|\\*|\\+|\\-)", "\\\\$1")
  }
}
